iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0

概念

每一個 selector 都會得到一個分數,而 specificity 就是加總每一個 selector 的分數,套用最高分的那組 CSS 樣式。實務上在寫 selctor 時,會盡量簡單化,避免要寫一個更高分的 selector 或是強迫使用 !important 去覆蓋樣式。

Selector 分數
Universal selector 0
Element / pseudo-element selector 1
Class / pseudo-class selector / attribute selector 10
ID selector 100
Inline style 1000
!important 10000

例如:

a.my-class.another-class {
  color: rebeccapurple;
}

/* a -> 1 */
/* .my-class -> 10 */
/* .another-class -> 10 */
/* 總分為 21 points */

又或是將 selector 做分群,越具體、越明確的,由左至右排列 (id group —> class/attribute group —> element group),由左至右依序比較

例如:

a.my-class.another-class[href]:hover {
  color: lightgrey;
}

id group:0 個
class/attribute group:4 個 (.my-class、.another-class、[href]、:hover)
element group: 1 個 (a)

所以結果會是 0-4-1

再回顧 cascade 的判斷四階段:

  1. Importance
  2. Origin
  3. Specificity
  4. Position and order of appearance

由上至下執行這四個階段,如果執行到 Specificity 發現分數都一樣,才會判斷哪一組規則寫在最後面。


上一篇
The cascade
下一篇
Inheritance
系列文
一個人的朝聖:重啟對 CSS 的認識14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言